<template>
  <div>
    <search-pane
      :show="showSearchPane"
      @search="handleSearchDevice"
      @reset="resetDeviceQueryParams"
    >
      <search-item>
        <PDInput
          v-model="queryParams.deviceId"
          input-width="200px"
          description="设备编号"
        />
      </search-item>
      <search-item
        label="设备类型"
      >
        <el-select
          v-model="queryParams.typeId"
          size="mini"
          clearable
          filterable
          @clear="handleClear('typeId')"
        >
          <el-option
            v-for="item in deviceTypeList"
            :key="item.typeId"
            :label="item.name"
            :value="item.typeId"
          />
        </el-select>
      </search-item>

      <search-item
        label="单位名称"
      >
        <el-select
          v-model="queryParams.unitId"
          size="mini"
          clearable
          filterable
          @clear="handleClear('unitId')"
        >
          <el-option
            v-for="item in unitList"
            :key="item.unitId"
            :label="item.name"
            :value="item.unitId"
          />
        </el-select>
      </search-item>

      <search-item
        label="实验室"
      >
        <el-select
          v-model="queryParams.labId"
          size="mini"
          clearable
          filterable
          @clear="handleClear('labId')"
        >
          <el-option
            v-for="item in laboratoryList"
            :key="item.labId"
            :label="item.name"
            :value="item.labId"
          />
        </el-select>
      </search-item>
    </search-pane>

    <table-tool-bar
      v-model="showSearchPane"
      @handleCreate="handleCreateDevice"
      @refresh="fetchDevicePage"
    />

    <table-card>
      <el-table
        ref="filterTable"
        :data="deviceList"
        style="width: 100%"
      >

        <el-table-column
          prop="deviceId"
          label="设备编号"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="toDeviceRecord(scope.row.deviceId)"
            >
              {{ scope.row.deviceId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="设备名称"
        />
        <el-table-column
          prop="typeName"
          label="设备类型"
        />
        <el-table-column
          prop="labName"
          label="实验室"
        />
        <el-table-column
          prop="unitName"
          label="单位"
        />
        <el-table-column
          prop="state"
          label="状态"
        >
          <template slot-scope="scope">
            <el-tag
              disable-transitions
              :type="getState(scope.row.state)['tag']"
            >
              {{ getState(scope.row.state)['state'] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="200"
        >
          <template slot-scope="scope">
            <table-option-group
              type="button"
              @handleDelete="handleDeleteDevice(scope.row.deviceId)"
              @handleUpdate="handleUpdateDevice(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="fetchDevicePage"
      />
    </table-card>

    <form-dialog
      v-model="dialogFormVisible"
      :type="formType"
      @create="createDevice"
      @update="updateDevice"
    >
      <el-form
        ref="deviceForm"
        :rules="formRules"
        :model="tempDevice"
      >
        <el-form-item prop="id" label="设备号">
          <el-input v-model="tempDevice.deviceId" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="name" label="设备名称">
          <el-input v-model="tempDevice.name" style="width: 300px" />
        </el-form-item>
        <el-form-item prop="typeId" label="设备类型">
          <el-select
            v-model="tempDevice.typeId"
            size="small"
            clearable
            filterable
            placeholder="设备类型"
          >
            <el-option
              v-for="item in deviceTypeList"
              :key="item.name"
              :label="item.name"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="unitId" label="单位">
          <el-select
            v-model="tempDevice.unitId"
            size="small"
            clearable
            filterable
            placeholder="单位名称"
          >
            <el-option
              v-for="item in unitList"
              :key="item.unitId"
              :label="item.name"
              :value="item.unitId"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="labId" label="实验室">
          <el-select
            v-model="tempDevice.labId"
            size="small"
            clearable
            filterable
            placeholder="实验室"
          >
            <el-option
              v-for="item in laboratoryList"
              :key="item.name"
              :label="item.name"
              :value="item.labId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </form-dialog>
  </div>
</template>

<script>
import SearchPane from '@/components/SearchPane/SearchPane'
import SearchItem from '@/components/SearchPane/SearchItem'
import PDInput from '@/components/SearchPane/PDInput'
import TableCard from '@/components/table/TableCard'
import TableToolBar from '@/components/table/TableToolBar'
import { addDevice, deleteDevice, pageDevices, updateDevice } from '@/api/device'
import FormDialog from '@/components/FormDialog/FormDialog'
import TableOptionGroup from '@/components/table/TableOptionGroup'
import { showSuccessTip } from '@/utils/simple-tips'
import { listUnits } from '@/api/unit'
import { listLaboratories } from '@/api/laboratory'
import Pagination from '@/components/Pagination'
import { listDeviceTypes } from '@/api/device-type'

export default {
  name: 'Device',
  components: { Pagination, TableOptionGroup, FormDialog, TableToolBar, TableCard, PDInput, SearchItem, SearchPane },
  props: {
    deviceId: {
      type: String,
      default: ''
    },
    unitId: {
      type: String
    },
    queryState: {
      type: Number
    }
  },
  data() {
    return {
      // search attr
      showSearchPane: true,
      queryParams: {
        pageSize: 5,
        pageNum: 1
      },
      total: 10,

      // form attr
      tempDevice: {

      },
      dialogFormVisible: false,
      formType: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      formRules: {

      },

      // table attr
      deviceList: [],

      // common attr
      unitList: [],
      laboratoryList: [],
      deviceTypeList: [],
      stateMap: [
        {
          tag: 'primary',
          state: '开启'
        },
        {
          tag: 'success',
          state: '关闭'
        },
        {
          tag: 'danger',
          state: '故障'
        }
      ]

    }
  },
  mounted() {
    if (this.deviceId !== '') {
      this.queryParams.deviceId = this.deviceId
    }
    if (this.unitId) {
      this.queryParams.unitId = this.unitId
    }
    if (this.queryState) {
      this.queryParams.state = this.queryState
    }
    this.fetchDevicePage()
    this.fetchUnitList()
    this.fetchLaboratoryList()
    this.fetchDeviceTypeList()
  },
  methods: {
    getState(state) {
      return this.stateMap[state]
    },

    fetchDevicePage() {
      pageDevices(this.queryParams).then(response => {
        this.deviceList = response.data.list
        this.total = response.data.total
      })
    },
    fetchUnitList() {
      listUnits().then(response => {
        this.unitList = response.data
      })
    },
    fetchLaboratoryList() {
      listLaboratories().then(response => {
        this.laboratoryList = response.data
      })
    },
    fetchDeviceTypeList() {
      listDeviceTypes().then(response => {
        this.deviceTypeList = response.data
      })
    },

    // region search relative function
    handleSearchDevice() {
      this.fetchDevicePage()
    },
    resetDeviceQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5
      }
    },
    handleClear(param) {
      this.queryParams[param] = undefined
    },
    // endregion

    // region form relative function
    resetTempDevice() {
      this.tempDevice = {}
    },
    handleCreateDevice() {
      this.resetTempDevice()
      this.formType = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['deviceForm'].clearValidate()
      })
    },
    createDevice() {
      this.$refs['deviceForm'].validate((valid) => {
        if (valid) {
          addDevice(this.tempDevice).then(() => {
            this.fetchDevicePage()
            this.dialogFormVisible = false
            showSuccessTip()
          })
        }
      })
    },
    handleUpdateDevice(row) {
      console.log(row)
      this.tempDevice = Object.assign({}, row)
      this.formType = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['deviceForm'].clearValidate()
      })
    },
    updateDevice() {
      this.$refs['deviceForm'].validate((valid) => {
        if (valid) {
          const tempDevice = Object.assign({}, this.tempDevice)
          updateDevice(tempDevice).then(() => {
            this.fetchDevicePage()
            this.dialogFormVisible = false
            showSuccessTip()
          })
        }
      })
    },
    handleDeleteDevice(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice(id).then(() => {
          this.dialogFormVisible = false
          this.fetchDevicePage()
          showSuccessTip()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // endregion

    // region router relative function
    toDeviceRecord(deviceId) {
      this.$router.push({
        name: 'DeviceRecord',
        params: {
          deviceId: deviceId
        }
      })
    }
    // endregion

  }
}

</script>

<style lang="scss" scoped>
</style>
